package com.yanchangapp.ui.fragment.home;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.yanchangapp.commom.MenuIdentify;
import com.yanchangapp.ui.activity._n_manage.DailyPlanActivity;
import com.yanchangapp.ui.activity._n_manage.HistoryPlanActivity;
import com.yanchangapp.ui.activity._n_manage.LinkManActivity;
import com.yanchangapp.ui.activity._n_manage.LinkWorkItemActivity;
import com.yanchangapp.ui.activity._n_manage.WorkItemActivity;
import com.yanchangapp.ui.activity.mail.WebViewActivity;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.zxl.baselib.ui.base.BaseFragment;
import com.zxl.baselib.util.ui.UIUtils;
import com.yanchangapp.R;
import com.yanchangapp.adapter.HomeIconsAdapter;
import com.yanchangapp.adapter.WaitDoneAdapter;
import com.yanchangapp.model.bean.MenuIcons;
import com.yanchangapp.model.cache.UserCache;
import com.yanchangapp.model.response.HomeBannerResponse;
import com.yanchangapp.model.response.MenuResponse;
import com.yanchangapp.model.response.WaitDoneResponse;
import com.yanchangapp.ui.activity.base.MainActivity;
import com.yanchangapp.ui.activity.mail.MailHomeActivity;
import com.yanchangapp.ui.activity.manage.ManageHomeActivity;
import com.yanchangapp.ui.activity.msg.MessageActivity;
import com.yanchangapp.ui.activity.purchase.PurchaseHomeActivity;
import com.yanchangapp.ui.presenter.HomeFgPresenter;
import com.yanchangapp.ui.view.HomeFgView;
import com.yanchangapp.util.GlideImageLoader;
import java.util.ArrayList;
import java.util.List;

/**
 * 主页
 *
 * 获得菜单...
 */
import butterknife.BindView;

import static com.yanchangapp.commom.MenuIdentify.MAIL_FIRST;
import static com.yanchangapp.commom.MenuIdentify.MANAGE;
import static com.yanchangapp.commom.MenuIdentify.PURCHASE;

public class HomeFragment extends BaseFragment<HomeFgView, HomeFgPresenter> implements HomeFgView {
    @BindView(R.id.tvCompanyWelcome)
    TextView tvCompanyWelcome;
    @BindView(R.id.tvTotalNum)
    TextView tvTotalNum;
    @BindView(R.id.ivMessage)
    ImageView ivMessage;
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.rvTotalMenu)
    RecyclerView rvTotalMenu;
    @BindView(R.id.tvPlansDetail)
    TextView tvPlansDetail;
    @BindView(R.id.rvNextPlan)
    RecyclerView rvNextPlan;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;
    // 图片提示...
    private List<String> mImages = new ArrayList<>();
    private List<HomeBannerResponse.DataBean> mBannerOriginList = new ArrayList<>();
    private List<WaitDoneResponse.DataBean> mWaitDoneList = new ArrayList<>();
    private WaitDoneAdapter mWaitDoneAdapter;
    private HomeIconsAdapter mHomeIconsAdapter;
    private List<MenuIcons> mMenuIconsList = new ArrayList<>();
    public static List<MenuResponse.Bean> mStaticMenuList;
    @Override
    public void init() {

    }

    @Override
    protected int provideContentViewId() {
        return R.layout.fragment_home_home;
    }

    @Override
    protected HomeFgPresenter createPresenter() {
        return new HomeFgPresenter((MainActivity)getActivity());
    }

    @Override
    public void initView(View rootView) {
        Log.e("全局", "初始化HomeFragment了" );
        banner.setImageLoader(new GlideImageLoader())
                .isAutoPlay(true)
                .setDelayTime(5000)
                .setIndicatorGravity(BannerConfig.CENTER);
        setWelcomeText();
        initIconsRv();
        initNextPlanRv();
        // 查询轮播图
        mPresenter.queryBannerImages();
        // 查询待完成的计划
        mPresenter.queryWaitDoneList();
        // 查询菜单列表
        mPresenter.queryMenuLists();

        // 设置点击事件...
        ivMessage.setOnClickListener(v -> MessageActivity.show(_mActivity));
        // 设置加载更多为false
        mRefreshLayout.setEnableLoadMore(false);

        setRefreshListener();

    }

    private void setRefreshListener() {
        mRefreshLayout.setOnRefreshListener(refreshLayout -> UIUtils.postTaskDelay(new Runnable() {
            @Override
            public void run() {
                refreshLayout.finishRefresh();
                // 查询轮播图
                mPresenter.queryBannerImages();
                // 查询待完成的计划
                mPresenter.queryWaitDoneList();
                // 查询菜单列表
                mPresenter.queryMenuLists();
            }
        },2000));
    }

    // 设置顶部Icons 并设置点击事件
    private void initIconsRv(){
        mHomeIconsAdapter = new HomeIconsAdapter(R.layout.item_home_iocns,mMenuIconsList);
        mHomeIconsAdapter.setOnItemClickListener((adapter, view, position) -> {
            int id = mMenuIconsList.get(position).getId();
            if (id == MAIL_FIRST.id){
                jumpToActivity(MailHomeActivity.class);
            }else if (id == MANAGE.id){
                jumpToActivity(ManageHomeActivity.class);
            }else if (id == PURCHASE.id){
                jumpToActivity(PurchaseHomeActivity.class);
            }
        });
        rvTotalMenu.setLayoutManager(new GridLayoutManager(getActivity(),3, LinearLayoutManager.VERTICAL,false));
        rvTotalMenu.setAdapter(mHomeIconsAdapter);
    }

    // 初始化代办的RecyclerView
    private void initNextPlanRv(){
        mWaitDoneAdapter = new WaitDoneAdapter(R.layout.item_wait_done,mWaitDoneList);
        rvNextPlan.setLayoutManager(new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false));
        mWaitDoneAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                int menuID =  mWaitDoneList.get(position).getMenuId();
                if (menuID == MenuIdentify.N_WORK_ITEM.id){
                    WorkItemActivity.show(getActivity());
                }else if (menuID == MenuIdentify.N_DAILY_PLAN.id){
                    DailyPlanActivity.show(getActivity());
                }else if (menuID == MenuIdentify.N_HISTORY_PLAN.id){
                    HistoryPlanActivity.show(getActivity());
                }else if (menuID == MenuIdentify.N_LINK_MAN.id){
                    LinkManActivity.show(getActivity());
                }else if (menuID == MenuIdentify.N_LINK_WORK_ITEM.id){
                    LinkWorkItemActivity.show(getActivity());
                }
            }
        });
        rvNextPlan.setAdapter(mWaitDoneAdapter);
    }

    // 懒加载
    @Override
    public void initData() {
    }

    // 懒加载
    @Override
    public void initListener() {
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (hidden){
            Log.e("轮播图", "隐藏了: ");
            if (banner != null && mImages.size() != 0){
                banner.stopAutoPlay();
            }
        }else {
            Log.e("轮播图", "显示了: ");
            if (banner != null && mImages.size() != 0){
                banner.startAutoPlay();
            }
            mPresenter.queryWaitDoneList();
        }
    }

    public void homeShow(){
        Log.e("轮播图", "homeShow:  展示了" );
        if (banner != null && mImages.size() != 0){
            banner.startAutoPlay();
        }
        if (tvTotalNum != null){
            mPresenter.queryWaitDoneList();
        }
    }

    public void homeHidden(){
        Log.e("轮播图", "homeShow:  隐藏了" );
        if (banner != null && mImages.size() != 0){
            banner.stopAutoPlay();
        }
    }

    @Override
    public void onDestroy() {
        mStaticMenuList = null;
        super.onDestroy();
    }

    // 设置轮播开始
    private void setBannerOk(){
        if (mImages.size() != 0) {
            banner.setImages(mImages).start();
        }
    }

    // 设置欢迎词
    private void setWelcomeText(){
        tvCompanyWelcome.setText(getString(R.string.welcome_text, UserCache.getCompanyName()));
    }

    // banner图回调设置...
    @Override
    public void getBannerSuccess(List<HomeBannerResponse.DataBean> originList, List<String> targetImages) {
        mBannerOriginList.clear();
        mImages.clear();
        mBannerOriginList.addAll(originList);
        mImages.addAll(targetImages);
        setBannerOk();
    }

    @Override
    public void getBannerFailure(String err) {
        UIUtils.showToast(err);
    }

    @Override
    public void getWaitDoneSuccess(int totalNum, List<WaitDoneResponse.DataBean> mList) {
        // 设置总数量

        tvTotalNum.setText(getString(R.string.total_plans,String.valueOf(totalNum)));
        // 刷新等待的item
        mWaitDoneList.clear();
        mWaitDoneList.addAll(mList);
        mWaitDoneAdapter.notifyDataSetChanged();


    }

    @Override
    public void getWaitDoneFailure(String msg) {

    }

    @Override
    public void getMenuListsFailure(String msg) {

    }

    @Override
    public void getMenuListsSuccess(List<MenuResponse.Bean> list,List<MenuIcons> menuIcons) {
        // 进行加载
        this.mMenuIconsList.clear();
        this.mMenuIconsList.addAll(menuIcons);
        mHomeIconsAdapter.notifyDataSetChanged();

        // 设置静态数据
        mStaticMenuList = new ArrayList<>();
        mStaticMenuList.clear();
        if (list != null){
            mStaticMenuList.addAll(list);
        }
    }

}
